import { Controller, Get, Post, Body, Patch, Param, UploadedFile, UseInterceptors, UploadedFiles } from '@nestjs/common';
import { FileService } from './file.service';
import { CreateFileDto } from './dto/create-file.dto';
import { UpdateFileDto } from './dto/update-file.dto';
import { FileInterceptor, FilesInterceptor, AnyFilesInterceptor } from '@nestjs/platform-express';
import { Public } from 'src/common/JWT/public.decorator';
import { BusinessException } from 'src/common/exceptions/business.exception.filter';
import * as path from 'path';
import { fileStorage } from 'src/utils/file-storage';
@Controller('file')
export class FileController {
    constructor(private readonly fileService: FileService) { }
    //上传单个文件
    @Public()
    @Post('file')
    @UseInterceptors(FileInterceptor('file'))
    uploadFile(@UploadedFile() file: Express.Multer.File,) {
        console.log(file);
        return file
    }

    //上传多个文件
    @Public()
    @Post('files')
    @UseInterceptors(FilesInterceptor('file'))
    uploadFiles(@UploadedFiles() files: Array<Express.Multer.File>,) {
        console.log(files);

    }

    //上传带其他参数的文件
    @Public()
    @Post('filem')
    @UseInterceptors(AnyFilesInterceptor())
    uploadFileAndOther(@Body() objDto, @UploadedFiles() files: Array<Express.Multer.File>,) {
        console.log(files);
        console.log(objDto)
        return files
    }
    //formData上传文件
    @Public()
    @Post('formdataFiile')
    @UseInterceptors(
        FileInterceptor('formdataFiile',//参数名称 formdataFiile
            {
                dest: './public/uploads',
            }),
    )
    uploadFileData(@UploadedFile() file: Express.Multer.File, @Body() body) {
        console.log('body', body);
        console.log('file', file);
    }

    @Public()
    @Post('picture')//参数名称 picture
    @UseInterceptors(
        FileInterceptor('picture', {
            dest: './public/uploads',
            storage: fileStorage,
            // 限制图片大小
            limits: {
                fileSize: 1024 * 1024 * 2 // 2M
            },
            // 限制图片格式
            fileFilter(req, file, callback) {
                const extname = path.extname(file.originalname);
                if (['.png', '.jpg', '.gif', '.jpeg'].includes(extname)) {
                    callback(null, true);
                } else {
                    callback(new BusinessException('只能上传图片！'), false);
                }
            }
        })
    )
    uploadPicture(@UploadedFile() file: Express.Multer.File) {
        return file;
    }


}
